import axios from 'axios';
import router from './router'

const API_BASE_URL = 'http://localhost:8090';
const TOKEN_KEY = 'token';

export default {

    get: (url, params = {}, headers = {}) => {
        const token = localStorage.getItem(TOKEN_KEY); // 获取Token，这里假设从localStorage获取
        if (token) {
            headers.Authorization = token; // 添加Authorization header
        }

        return axios.get(`${API_BASE_URL}${url}`, { params, headers })
            .then(response => response.data)
            .catch(error => {
                console.log(error.response.data);
                if (error.response.data.code === 401){
                    router.replace('/login');
                }
                return;
            });
    },

    post: (url, data, headers = {}) => {
        const token = localStorage.getItem(TOKEN_KEY);
        if (token) {
            headers.Authorization = token;
        }

        return axios.post(`${API_BASE_URL}${url}`, data, { headers })
            .then(response =>response.data)
            .catch(error => {
                console.log(error.response.data);
                if (error.response.data.code === 401){
                    router.replace('/login');
                }
                return;
            });
    }
};